package com.shujia.spark.core

import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}

object Demo7GroupByKey {

  def main(args: Array[String]): Unit = {
    val conf: SparkConf = new SparkConf()
      .setAppName("map")
      .setMaster("local")

    //spark  上下文对象
    val sc = new SparkContext(conf)

    val linesRDD: RDD[String] = sc.textFile("data/words.txt")

    val wordsRDD: RDD[String] = linesRDD.flatMap(_.split(","))

    //将rdd转换成kv格式
    val kvRDD: RDD[(String, Int)] = wordsRDD.map(word => (word, 1))

    /**
      * groupByKey: 通过key进行分组，将valye 方法迭代器中
      * groupBy： 指定一个分组的列，
      *
      * 都会产生shuffle
      */

    val groupByKeyRDD: RDD[(String, Iterable[Int])] = kvRDD.groupByKey()

    val countyRDD: RDD[(String, Int)] = groupByKeyRDD.map {
      case (word: String, values: Iterable[Int]) =>
        (word, values.sum)
    }
    countyRDD.foreach(println)


    val groupByRDD: RDD[(String, Iterable[(String, Int)])] = kvRDD.groupBy(kv => kv._1)


  }


}
